const Controller = require('egg').Controller;

const jwt = require('jsonwebtoken')

class LoginController extends Controller {
    //登录
    async login() {
        const { ctx, app } = this

        const { username, password } = ctx.request.body

        const data = await app.mysql.get('userlist', { username, password })

        if (data) {
            const token = jwt.sign({ ...data }, '1901A', { expiresIn: '15m' })

            ctx.body = {
                code: 0,
                msg: '登录成功',
                token,
                data
            }
        } else {
            ctx.body = {
                code: 1,
                msg: '登录失败',
            }
        }
    }

    //注册
    async register() {
        const { ctx, app } = this

        const { username, password } = ctx.request.body

        const data = await app.mysql.get('userlist', { username })

        if (data) {
            ctx.body = {
                code: 3,
                msg: '账号已存在'
            }
        }
        else {
            await app.mysql.insert('userlist', { username, password })
            ctx.body = {
                code: 4,
                msg: '注册成功'
            }
        }
    }
}

module.exports = LoginController;